<template>
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <template #imageUrl="{ record }">
      <ImagePreview :image-list="[{ src: record.url, width: 80 }]" />
    </template>
  </BasicTable>
</template>

<script lang="ts" name="weixin-mp-menu" setup>
import { ref, onMounted, watch, reactive } from 'vue'
import { BasicTable, TableAction } from '/@/components/Table';
import { ImagePreview } from '/@/components/Preview/index';
import { useListPage } from '/@/hooks/system/useListPage'
import { materialImageColumn } from '../../mpMaterial/data'
import { MediaFileType } from '../../mpMaterial/model'
import { pageMpMaterial } from '../../mpMaterial/api'
import { useMessage } from "/@/hooks/web/useMessage";

const { createMessage } = useMessage()
const emit = defineEmits(['update:objData']);
const props = defineProps({
  objData: { type: Object, required: true },
})

const data = reactive<any>({
  materialUrl: ''
})

// 列表页面公共参数、方法
const { prefixCls, tableContext } = useListPage({
  designScope: 'weixin-mp-material-image',
  tableProps: {
    api: pageMpMaterial,

    beforeFetch: (params) => {
      params.accountId = props.objData.accountId
      params.type = MediaFileType.IMAGE
    },
    columns: materialImageColumn,
    formConfig: {
      showResetButton: false,
      showSubmitButton: false
    },
    showActionColumn: false,
    showTableSetting: false,
    useSearchForm: false,
    bordered: false,
    actionColumn: {
      width: 120,
    },
  }
})
const [registerTable, { getForm, reload }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;

watch(
  () => props.objData.accountId,
  (accountId: string) => {
    if (accountId) {
      reload()
    }
  }
);

onMounted(() => {
  if (props.objData.accountId) {
    reload()
  }
})

const handleSelectedRow = () => {
  if (selectedRows.value.length > 1) {
    createMessage.warning('一次只能选择一个素材')
    throw new Error('一次只能选择一个素材')
  } 
  const rows = selectedRows.value[0]
  const data : any = {
    ...props.objData, 
    url: rows.url,
    mediaId: rows.mediaId,
    name: rows.name,
  }
  emit('update:objData', data)
}

defineExpose({
  selectedRowKeys, handleSelectedRow
})

</script>